package com.dimeng.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;

import com.dimeng.utils.AsyncImageLoader;
import com.dimeng.utils.AsyncImageLoader.ImageCallback;

/**
 * @author write by ccn<br>
 *         <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-7-02 下午7:11:00<br>
 *          descrition:美图视图的item视图缓存
 */
public class ImageSwitcherGalleryAdapter extends BaseAdapter {
	private Context context;
	private Gallery gallery;
	private ImageSwitcher imageSwitcher;
	private List<String> list;

	public ImageSwitcherGalleryAdapter(Context c, List<String> list, Gallery gallery,ImageSwitcher imageSwitcher) {
		context = c;
		this.list = list;
		this.gallery = gallery;
		this.imageSwitcher = imageSwitcher;
	}
	
	public View getView(final int position, View convertView, ViewGroup parent) {
		ImageView imageView = (ImageView) convertView;
		if (imageView == null) {
			imageView = new ImageView(context);
			imageView.setAdjustViewBounds(true);  
			imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
			imageView.setPadding(30, 10, 10, 0);
		}
		String imageUrl = list.get(position);
		if (null != imageUrl) {
			imageView.setTag(imageUrl);
			Drawable cachedImage = AsyncImageLoader.getInstance().loadDrawable(imageUrl, new ImageCallback() {
				public void imageLoaded(Drawable imageDrawable,String imageUrl) {
					ImageView imageViewByTag = (ImageView) gallery.findViewWithTag(imageUrl);
					if (imageViewByTag != null) {
						imageViewByTag.setImageDrawable(imageDrawable);
					}
				}
			});
			if(0 == position)
				imageSwitcher.setImageDrawable(cachedImage);
			imageView.setImageDrawable(cachedImage);
		}
		return imageView;
	}
	public int getCount() {
		return list.size();
	}
	public Object getItem(int position) {
		ImageView imgv = (ImageView) getView(position,null,null);
		return imgv;
	}
	public long getItemId(int position) {
		return position;
	}
}
